package org.footito.android.data;

import java.io.File;
import java.util.concurrent.RejectedExecutionException;

import org.footito.android.R;
import org.footito.android.data.update.LoadAsyncTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import org.footito.android.tools.Log;

public class Team {
	private String name;
	private String pictureLink;
	private String link;
	private int id;
	private Bitmap picture;

	public static final String PICTURE_FOLDER = Environment.getExternalStorageDirectory() + File.separator + "footito" + File.separator + "pictures"
			+ File.separator;

	/**
	 * @param name
	 * @param picture
	 * @param link
	 * @param id
	 */
	public Team(String name, String pictureLink, String link, int id) {
		super();
		this.name = name;
		this.pictureLink = pictureLink;
		this.link = link;
		this.id = id;
	}

	/**
	 * @return the pictureLink
	 */
	public String getPictureLink() {
		return pictureLink;
	}

	/**
	 * @param pictureLink
	 *            the pictureLink to set
	 */
	public void setPictureLink(String pictureLink) {
		this.pictureLink = pictureLink;
	}

	/**
	 * @return the picture
	 */
	public Bitmap getPicture(Context context) {
		if (picture == null) {
			String targetPath = Team.PICTURE_FOLDER;
			String targetName = id + ".jpg";
			picture = BitmapFactory.decodeFile(targetPath + targetName);
		}

		if (picture == null) {
			return BitmapFactory.decodeResource(context.getResources(), R.drawable.blason_loading);
		} else {
			return picture;
		}
	}

	/**
	 * @param picture
	 *            the picture to set
	 */
	public void setPicture(Bitmap picture) {
		this.picture = picture;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the link
	 */
	public String getLink() {
		return link;
	}

	/**
	 * @param link
	 *            the link to set
	 */
	public void setLink(String link) {
		this.link = link;
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	public void loadPicture(Context context) {
		String targetPath = Team.PICTURE_FOLDER;
		String targetName = id + "";

		Bitmap bitmap = BitmapFactory.decodeFile(targetPath + targetName);
		if (bitmap == null) {
			LoadAsyncTask taskLoadPicture = new LoadAsyncTask(targetPath, targetName, this);
			try {
				taskLoadPicture.execute((Void[]) null);
			} catch (RejectedExecutionException e) {
				Log.w("Exception: " + "RejectedExecutionException: " + e.getMessage());
			}
		} else {
			this.setPicture(bitmap);
		}
	}
}
